﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECRMS.Biz.Dom;
using ECRMS.Data;
using System.Data.Linq;
using ECRMS.Common;

namespace ECRMS.Biz
{
    public class CtUserLogic
    {
        public CtServiceResult<CtUser> Login(string username, string password)
        {
            try
            {
                using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
                {
                    List<CSRLogin> list = dataContext.GetTable<CSRLogin>().ToList();
                    CSRLogin login = dataContext.GetTable<CSRLogin>().FirstOrDefault(p => p.Username == username && p.Password == password);

                    if (login == null)
                    {
                        return new CtServiceResult<CtUser>
                        {
                            Message = "login_error",
                            Status = 0
                        };
                    }
                    return new CtServiceResult<CtUser>
                    {
                        Data = (from a in dataContext.GetTable<CSRLogin>()
                                join b in dataContext.GetTable<CSRUser>() on a.UserRefId equals b.UserRefId
                                join c in dataContext.GetTable<CSRCorp>() on b.CorpRefId equals c.CorpRefId
                                where a.Username ==username && a.Password==password
                                select new CtUser
                                {
                                    Email = b.Email,
                                    Gender = b.Gender,
                                    Name = b.Name,
                                    Functions=GetFunctions(a,dataContext),
                                    CorpRefId = c.CorpRefId,
                                    Login = new CtLogin
                                    {
                                        CreateDate=a.CreateDate,
                                        Password = a.Password,
                                        Username = a.Username,
                                        UserRefId = a.UserRefId,
                                        UserTypeId = a.UserTypeId
                                    }

                                }).ToList()[0],
                        Status = 1
                    };
                }
            }
            catch (Exception)
            {
                return new CtServiceResult<CtUser>
                {
                    Message = "try_catch_exception",
                    Status = 0
                };
            }

        }

        public CtServiceResult<List<CtUser>> GetEmployeesByCorpId(Guid corpId)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    return new CtServiceResult<List<CtUser>>
                    {
                        Data = (from a in dataContext.GetTable<CSRLogin>()
                                join b in dataContext.GetTable<CSRUser>() on a.UserRefId equals b.UserRefId
                                join c in dataContext.GetTable<CSRCorp>() on b.CorpRefId equals c.CorpRefId
                                where c.CorpRefId == corpId && a.IsDisabled == false
                                select new CtUser
                                {
                                    Email = b.Email,
                                    Functions = GetFunctions(a, dataContext),
                                    Gender = b.Gender,
                                    Name = b.Name,
                                    CorpRefId = c.CorpRefId,
                                    Login = new CtLogin
                                    {
                                        CreateDate = a.CreateDate,
                                        Password = a.Password,
                                        Username = a.Username,
                                        UserRefId = a.UserRefId,
                                        UserTypeId = a.UserTypeId
                                    }

                                }).ToList()
                                ,
                        Status = 1

                    };
                }
                catch (Exception)
                {

                    return new CtServiceResult<List<CtUser>>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }


            }
        }


        public CtServiceResult<List<CtUser>> Insert(CtUser userInfo)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    //判断是否重名
                    if (dataContext.GetTable<CSRLogin>().FirstOrDefault(p => p.Username == userInfo.Login.Username) != null)
                    {
                        return new CtServiceResult<List<CtUser>>
                        {
                            Message = "message_username_repeat",
                            Status = 0
                        };
                    }

                    CSRLogin login = new CSRLogin
                    {
                        CreateDate=DateTime.Now,
                        IsDisabled=false,
                        Password=userInfo.Login.Password,
                        Username=userInfo.Login.Username,
                        UserRefId=userInfo.Login.UserRefId,
                        UserTypeId=(int)AuthorityEnum.CorporationClientUser

                    };
                    CSRUser user =new CSRUser{
                        CorpRefId=userInfo.CorpRefId,
                        Email=userInfo.Email,
                        Gender=userInfo.Gender,
                        IsDisabled=false,
                        Name=userInfo.Name,
                        UserRefId=userInfo.Login.UserRefId
                    };
                    dataContext.GetTable<CSRLogin>().InsertOnSubmit(login);
                    dataContext.GetTable<CSRUser>().InsertOnSubmit(user);

                    if (userInfo.Functions != null && userInfo.Functions.ToArray().Length >= 1)
                    {
                        List<CSRUserFunction> efs = new List<CSRUserFunction>();
                        foreach (int funcitonRefId in userInfo.Functions)
                        {
                            efs.Add(new CSRUserFunction
                            {
                                FunctionRefId = funcitonRefId,
                                UserFunctionRefId = Guid.NewGuid(),
                                UserRefId = userInfo.Login.UserRefId
                            });
                        }
                        dataContext.GetTable<CSRUserFunction>().InsertAllOnSubmit(efs);
                    }

                    dataContext.SubmitChanges();
                    return GetEmployeesByCorpId(userInfo.CorpRefId);
                }
                catch (Exception)
                {
                    //返回异常
                    return new CtServiceResult<List<CtUser>>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }

            }
        }

        //删除或者更新
        public CtServiceResult<List<CtUser>> Update(CtUser userInfo)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    if (userInfo.Disabled)
                    {
                        //判断是否重名
                        if (dataContext.GetTable<CSRLogin>().FirstOrDefault(p => p.Username == userInfo.Login.Username && p.UserRefId != userInfo.Login.UserRefId) != null)
                        {
                            return new CtServiceResult<List<CtUser>>
                            {
                                Message = "message_username_repeat",
                                Status = 0
                            };
                        }
                        CSRLogin login = dataContext.GetTable<CSRLogin>().FirstOrDefault(p => p.UserRefId == userInfo.Login.UserRefId);
                        CSRUser user = dataContext.GetTable<CSRUser>().FirstOrDefault(p => p.UserRefId == userInfo.Login.UserRefId);

                        //login.CreateDate 暂时不修改了
                        login.Password = userInfo.Login.Password;
                        login.Username = userInfo.Login.Username;
                        login.UserRefId = userInfo.Login.UserRefId;

                        user.Email = userInfo.Email;
                        user.Gender = userInfo.Gender;
                        user.Name = userInfo.Name;



                    }
                    else//删除
                    {
                        CSRLogin login = dataContext.GetTable<CSRLogin>().FirstOrDefault(p => p.UserRefId == userInfo.Login.UserRefId);
                        CSRUser user = dataContext.GetTable<CSRUser>().FirstOrDefault(p => p.UserRefId == userInfo.Login.UserRefId);

                        login.IsDisabled = true;
                        login.IsDisabled = true;

                    }                        
                    //删除原先的权限分配
                    dataContext.GetTable<CSRUserFunction>().DeleteAllOnSubmit(dataContext.GetTable<CSRUserFunction>().Where(p => p.UserRefId == userInfo.CorpRefId));

                    if (userInfo.Functions != null && userInfo.Functions.ToArray().Length >= 1&&!userInfo.Disabled)
                    {
                        List<CSRUserFunction> efs = new List<CSRUserFunction>();
                        foreach (int funcitonRefId in userInfo.Functions)
                        {
                            efs.Add(new CSRUserFunction
                            {
                                FunctionRefId = funcitonRefId,
                                UserFunctionRefId = Guid.NewGuid(),
                                UserRefId = userInfo.Login.UserRefId
                            });
                        }
                        dataContext.GetTable<CSRUserFunction>().InsertAllOnSubmit(efs);
                    }

                    dataContext.SubmitChanges();
                    return GetEmployeesByCorpId(userInfo.CorpRefId);

                }
                catch (Exception)
                {
                    //返回异常
                    return new CtServiceResult<List<CtUser>>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }

            }
        }

        private List<int> GetFunctions(CSRLogin login, CSRManagerSystemDBDataContext dataContext)
        {
            List<int> functions = new List<int>();
            List<CSRUserFunction> list = dataContext.GetTable<CSRUserFunction>().Where(p => p.UserRefId == login.UserRefId).ToList();
            if (functions != null)
            {
                for (int i = 0; i < list.ToArray().Length; i++)
                {
                    functions.Add(list[i].FunctionRefId);
                }
            }
            return functions;
        }
    }
}
